package com.example.knowledgeget1.FileOperate;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class FileList {

    public static void main(String[] args) {
        String apiKey = "sk-273f70a32e7647a5890925d82aa94a2b";
        String url = "http://dashscope.aliyuncs.com/compatible-mode/v1/files";

        try {
            // 创建HttpClient实例
            HttpClient client = HttpClient.newHttpClient();

            // 创建HttpRequest实例
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Authorization", "Bearer " + apiKey)
                    .GET()
                    .build();

            // 发送请求
            HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());

            int statusCode = response.statusCode();
            if (statusCode == 301 || statusCode == 302) {
                // 获取重定向的新位置
                URI newLocation = URI.create(response.headers().firstValue("Location").orElse(null));

                if (newLocation != null) {
                    // 构建新的HttpRequest针对新的位置
                    HttpRequest redirectedRequest = HttpRequest.newBuilder()
                            .uri(newLocation)
                            .header("Authorization", "Bearer " + apiKey)
                            .GET()
                            .build();

                    // 再次发送请求
                    HttpResponse<String> finalResponse = client.send(redirectedRequest, HttpResponse.BodyHandlers.ofString());
                    System.out.println(finalResponse.body());
                    System.out.println("Final Status Code: " + finalResponse.statusCode());
                } else {
                    System.err.println("No Location header found in the redirect response.");
                }
            } else {
                System.err.println("Unexpected status code: " + statusCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}